package com.srwl.mytx.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.AdvertisementOrderRecordAdapter;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.Advertisement;
import com.srwl.mytx.domain.AdvertisementOrder;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AdvertisementOrderService;
import com.srwl.mytx.service.AdvertisementService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.NumberInputDialog;
import com.srwl.mytx.widget.PayPasswordDialog;
import com.srwl.mytx.widget.TimeSelectDialog;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 广告详情页面
 */
public class AdvertisementDetailActivity extends BaseActivity {
    private static final int REQUEST_CODE_TO_SET_ADVERTISEMENT_CONTENT = 1;
    private static final String TAG = "RechargeDetailActivity";

    public static void startActivity(Context context, String advertisementId) {
        context.startActivity(new Intent(context, AdvertisementDetailActivity.class).putExtra("advertisementId", advertisementId));
    }

    public static void startActivity(Activity activity, Advertisement advertisement, int requestCode) {
        activity.startActivityForResult(new Intent(activity, AdvertisementDetailActivity.class).putExtra("advertisement", advertisement), requestCode);
    }

    @BindView(R.id.tv_deposit)
    TextView tv_deposit;
    @BindView(R.id.tv_deposit_tips)
    TextView tv_depositTips;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_id)
    TextView tv_Id;
    @BindView(R.id.tv_created)
    TextView tv_created;


    @BindView(R.id.tv_modify_offer)
    TextView tv_modifyOffer;
    @BindView(R.id.tv_set_advertisement)
    TextView tv_setAdvertisement;
    @BindView(R.id.tv_modify_time)
    TextView tv_modifyTime;
    @BindView(R.id.tv_increment_deposit)
    TextView tv_incrementDeposit;
    @BindView(R.id.tv_revoke_deposit)
    TextView tv_revokeDeposit;
    @BindView(R.id.tv_customer_service)
    TextView tv_customerService;
    @BindView(R.id.rv_orders)
    RecyclerView rv_orders;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    @BindView(R.id.driver)
    View driver;
    @BindView(R.id.driver_0)
    View driver_0;
    @BindView(R.id.driver_1)
    View driver_1;
    @BindView(R.id.driver_2)
    View driver_2;

    private Advertisement advertisement;
    private String advertisementId;
    private List<AdvertisementOrder> ordersList = new ArrayList<>();
    private AdvertisementOrderRecordAdapter orderRecordAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advertisement_detail);
        ButterKnife.bind(this);
        advertisement = getIntent().getParcelableExtra("advertisement");
        if (advertisement != null) {
            setupViews();
            advertisementId = advertisement.getId();
        } else {
            advertisementId = getIntent().getStringExtra("advertisementId");
            loadAdvertisementData();
        }
        loadOrders();
        tv_customerService.setOnClickListener(v -> contactCustomerService());
        rv_orders.setLayoutManager(new LinearLayoutManager(this));
        orderRecordAdapter = new AdvertisementOrderRecordAdapter(this, ordersList);
        rv_orders.setAdapter(orderRecordAdapter);
    }

    private void loadAdvertisementData() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(AdvertisementService.class)
                .queryAdvertisementInfoById(advertisementId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            return;
                        }

                        Object data = body.getData();
                        if (data != null) {
                            JSONObject jsonObject = (JSONObject) data;
                            advertisement = jsonObject.toJavaObject(Advertisement.class);
                            setupViews();

                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        t.printStackTrace();
                    }
                });
    }

    private void loadOrders() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(AdvertisementOrderService.class)
                .queryAdvertisementOrders(advertisementId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            return;
                        }

                        Object data = body.getData();
                        if (data != null) {
                            JSONArray jsonObject = (JSONArray) data;
                            List<AdvertisementOrder> orders = jsonObject.toJavaList(AdvertisementOrder.class);
                            if (orders.size() != 0) {
                                ordersList.addAll(orders);
                                orderRecordAdapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        t.printStackTrace();
                    }
                });
    }

    private void setupViews() {
        Double deposit = advertisement.getDeposit();
        Double amount = advertisement.getAmount();
        tv_deposit.setText(Utils.moneyFormat(deposit));
        tv_incrementDeposit.setOnClickListener(v -> showDepositInputDialog());
        if (advertisement.getStatus() == Constant.ADVERTISEMENT_STATUS_REVOKE) {
            tv_depositTips.setText("保证金已退回");
            onDepositEqualZero();
        } else if (deposit.compareTo(amount) < 0) {
            tv_depositTips.setText("保证金不足");
            //保证金不足的情况，也有可能刚好为0，这时候，只显示增加保证金的按键
            if (deposit.compareTo(0d) == 0) {
                onDepositEqualZero();
            } else {
                onDepositNotEnough();
            }
        } else {
            tv_depositTips.setText("保证金充足");
            onDepositEnough();
        }

        LiveRoom liveRoom = advertisement.getLiveRoom();
        tv_title.setText(advertisement.getTitle());
        if (liveRoom != null) {
            tv_title.setOnClickListener(v -> ChatRoomActivity.startActivity(this, liveRoom));
            tv_title.setTextColor(getResources().getColor(R.color.btn_blue_normal));
        }
        tv_amount.setText(Utils.moneyFormat(advertisement.getAmount()));
        tv_time.setText(advertisement.getTime().toString());
        tv_Id.setText(advertisement.getId());
        tv_created.setText(DateUtils.dateToString(advertisement.getCreated(), DateUtils.FORMAT_TIMESTAMP));

    }

    private void onDepositEnough() {
        tv_modifyOffer.setOnClickListener(v -> showOfferInputDialog());
        tv_modifyTime.setOnClickListener(v -> showTimeSelectDialog());
        tv_revokeDeposit.setOnClickListener(v -> confirmRevokeDeposit());
        tv_setAdvertisement.setOnClickListener(v -> SetAdvertisementContentActivity.startActivity(this, advertisement, REQUEST_CODE_TO_SET_ADVERTISEMENT_CONTENT));
        driver.setVisibility(View.VISIBLE);
        tv_setAdvertisement.setVisibility(View.VISIBLE);
        driver_0.setVisibility(View.VISIBLE);
        tv_modifyOffer.setVisibility(View.VISIBLE);
        driver_1.setVisibility(View.VISIBLE);
        tv_modifyTime.setVisibility(View.VISIBLE);
        driver_2.setVisibility(View.VISIBLE);
        tv_revokeDeposit.setVisibility(View.VISIBLE);
    }

    private void onDepositEqualZero() {
        driver.setVisibility(View.GONE);
        tv_setAdvertisement.setVisibility(View.GONE);
        driver_0.setVisibility(View.GONE);
        tv_modifyOffer.setVisibility(View.GONE);
        driver_1.setVisibility(View.GONE);
        tv_modifyTime.setVisibility(View.GONE);
        driver_2.setVisibility(View.GONE);
        tv_revokeDeposit.setVisibility(View.GONE);
    }

    private void onDepositNotEnough() {
        driver_2.setVisibility(View.VISIBLE);
        tv_revokeDeposit.setVisibility(View.VISIBLE);
        tv_revokeDeposit.setOnClickListener(v -> confirmRevokeDeposit());
        driver.setVisibility(View.GONE);
        tv_setAdvertisement.setVisibility(View.GONE);
        driver_0.setVisibility(View.GONE);
        tv_modifyOffer.setVisibility(View.GONE);
        driver_1.setVisibility(View.GONE);
        tv_modifyTime.setVisibility(View.GONE);
        driver_2.setVisibility(View.GONE);
    }

    private void showOfferInputDialog() {
        NumberInputDialog dialog = NumberInputDialog.newInstance("输入新的出价", 0.1);
        dialog.setConfirmListener(new NumberInputDialog.ConfirmListener() {
            @Override
            public void confirm(Double amount) {
                if (amount.compareTo(advertisement.getDeposit()) > 0) {
                    ConfirmDialog dialog = new ConfirmDialog(AdvertisementDetailActivity.this, "提示", "出价不能高于剩余的保证金，建议先增加保证金，再修改出价");
                    dialog.show();
                    return;
                }
                if (amount.compareTo(advertisement.getAmount()) == 0) {
                    ConfirmDialog dialog = new ConfirmDialog(AdvertisementDetailActivity.this, "提示", "新出价不能和原出价相同");
                    dialog.show();
                    return;
                }

                changeOffer(amount);
            }
        });
        dialog.show(getSupportFragmentManager(), "");
    }

    private void changeOffer(Double amount) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        Advertisement updateAdvertisement = new Advertisement();
        updateAdvertisement.setId(advertisementId);
        updateAdvertisement.setAmount(amount);
        RetrofitManager.getInstance().createRequest(AdvertisementService.class)
                .changeOffer(updateAdvertisement)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_modifyTime, getString(R.string.system_busy));
                            return;
                        }
                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            showToast(tv_modifyTime, getString(R.string.system_busy));
                            return;
                        }
                        Log.i(TAG, "onResponse: 修改出价完成");
                        showToast(tv_modifyTime, "修改出价完成");
                        advertisement.setAmount(amount);
                        tv_amount.setText(Utils.moneyFormat(amount));
                        onAdvertisementChange();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });

    }


    private void showTimeSelectDialog() {
        TimeSelectDialog dialog = TimeSelectDialog.newInstance();
        dialog.setConfirmListener(new TimeSelectDialog.ConfirmListener() {
            @Override
            public void confirm(List<Integer> timeList) {
                changeTimes(timeList);
            }
        });
        dialog.show(getSupportFragmentManager(), "");
    }

    private void changeTimes(List<Integer> timeList) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        Advertisement body = new Advertisement();
        body.setId(advertisementId);
        body.setTime(timeList);
        RetrofitManager.getInstance().createRequest(AdvertisementService.class)
                .changeTimes(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_modifyTime, getString(R.string.system_busy));
                            return;
                        }
                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            showToast(tv_modifyTime, getString(R.string.system_busy));
                            return;
                        }
                        Log.i(TAG, "onResponse: 修改时间段完成");
                        showToast(tv_modifyTime, "修改时间段完成");
                        advertisement.setTime(timeList);
                        tv_time.setText(timeList.toString());
                        onAdvertisementChange();


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                    }
                });


    }

    private void confirmRevokeDeposit() {
        Double deposit = advertisement.getDeposit();
        if (deposit == null || deposit.compareTo(0d) == 0) {
            ConfirmDialog dialog = new ConfirmDialog(this, "提示", "保证金已经没有了");
            dialog.show();
        } else {
            ConfirmDialog dialog = new ConfirmDialog(this, "提示", "退回保证金后，广告将不再参与竞价", true);
            dialog.setConfirmListener(this::revokeDeposit);
            dialog.show();
        }
    }

    private void revokeDeposit() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(AdvertisementService.class)
                .revokeDeposit(advertisementId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_modifyTime, getString(R.string.system_busy));
                            return;
                        }
                        if (body.isError()) {
                            showToast(tv_modifyTime, getString(R.string.system_busy));
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            return;
                        }
                        Log.i(TAG, "onResponse: 退回保证金完成");
                        showToast(tv_modifyTime, "退回保证金完成");

                        Object data = body.getData();
                        if (data != null) {
                            if (data instanceof BigDecimal) {
                                BigDecimal deposit = (BigDecimal) data;
                                UserProfileManager.getInstance().setDeposit(deposit.doubleValue());
                            } else if (data instanceof Double) {
                                Double deposit = (Double) data;
                                UserProfileManager.getInstance().setDeposit(deposit);
                            } else {
                                Log.e(TAG, "onResponse: 返回数据类型错误");
                            }
                        }
                        advertisement.setDeposit(0.00);
                        advertisement.setStatus(Constant.ADVERTISEMENT_STATUS_REVOKE);
                        setupViews();
                        onAdvertisementChange();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                    }
                });

    }


    /**
     * 增加保证金
     */
    private void showDepositInputDialog() {
        double minlimit = 0.1;
        Double deposit = advertisement.getDeposit();
        Double amount = advertisement.getAmount();
        if (deposit == null || deposit.compareTo(Double.valueOf("0.00")) == 0) {
            minlimit = amount;
        } else if (amount.compareTo(deposit) > 0) {
            minlimit = BigDecimal.valueOf(amount).subtract(BigDecimal.valueOf(deposit)).setScale(2, RoundingMode.HALF_UP).doubleValue();
        }
        NumberInputDialog dialog = NumberInputDialog.newInstance("输入增加的金额", minlimit);
        dialog.setConfirmListener(new NumberInputDialog.ConfirmListener() {
            @Override
            public void confirm(Double amount) {
                /*String tips = "将增加保证金";
                new PayUtils(AdvertisementDetailActivity.this, deposit, tips, payPassword -> doOffer(offerAmount.doubleValue(), payPassword));*/

                if (amount <= UserProfileManager.getInstance().getPayLimit()) {
                    incrementDeposit(amount, "");
                } else {
                    String tips = "将增加保证金";
                    PayPasswordDialog payPasswordDialog = new PayPasswordDialog(AdvertisementDetailActivity.this, tips, amount);
                    payPasswordDialog.setOnConfirmListener(new PayPasswordDialog.OnConfirmListener() {
                        @Override
                        public void onCommit(String passWord) {
                            incrementDeposit(amount, passWord);
                        }
                    });
                    payPasswordDialog.show();
                }
            }
        });
        dialog.show(getSupportFragmentManager(), "");

    }

    /**
     * 增加保证金
     */
    private void incrementDeposit(Double deposit, String payPassword) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        Map<String, Object> body = new HashMap<>();
        body.put("advertisementId", advertisementId);
        body.put("deposit", deposit);
        body.put("payPassword", payPassword);
        RetrofitManager.getInstance().createRequest(AdvertisementService.class)
                .incrementDeposit(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.d(TAG, "onResponse: " + result.getMsg());
                            showToast(tv_customerService, result.getMsg());
                            return;
                        }
                        Log.i(TAG, "onResponse: 增加保证金完成");
                        showToast(tv_modifyTime, "增加保证金完成");
                        Object data = result.getData();
                        if (data != null) {
                            JSONObject jsonObject = (JSONObject) data;
                            Double advertisementDeposit = jsonObject.getDouble("advertisementDeposit");
                            advertisement.setDeposit(advertisementDeposit);
                            advertisement.setStatus(Constant.ADVERTISEMENT_STATUS_NORMAL);
                            setupViews();
                            onAdvertisementChange();
                            Double userDeposit = jsonObject.getDouble("userDeposit");
                            UserProfileManager.getInstance().setDeposit(userDeposit);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });

    }

    /**
     * 联系客服
     */
    private void contactCustomerService() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .customerService()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.d(TAG, "onResponse: " + result.getMsg());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User manualUser = object.toJavaObject(User.class);
                        manualUser.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(manualUser);
                        ChatActivity.startActivity(AdvertisementDetailActivity.this, manualUser);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });
    }


    private void onAdvertisementChange() {
        setResult(Activity.RESULT_OK, new Intent().putExtra("advertisement", advertisement));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == REQUEST_CODE_TO_SET_ADVERTISEMENT_CONTENT) {
            Advertisement updatedAdvertisement = data.getParcelableExtra("advertisement");
            if (updatedAdvertisement == null) return;
            advertisement = updatedAdvertisement;
        }

    }
}